package com.birdboot.core;

import com.birdboot.annotations.Controller;
import com.birdboot.annotations.RequestMapping;
import com.birdboot.controller.UserController;
import com.birdboot.http.HttpServletRequest;
import com.birdboot.http.HttpServletResponse;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 该类是SpringMVC框架提供的一个核心类,用于接手Web容器(如:Tomcat)处理请求的工作
 */
public class DispatcherServlet{
    private static DispatcherServlet instance = new DispatcherServlet();
    private static File baseDir;//类加载路径
    private static File staticDir;//static目录

    static {
        try {
            baseDir = new File(
                    DispatcherServlet.class.getClassLoader().getResource(".").toURI()
            );
            staticDir = new File(baseDir, "static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    private DispatcherServlet() {
    }

    public void service(HttpServletRequest request, HttpServletResponse response) {
        /*
            uri:
            /regUser?username=xxxx&password=xxx&....
            /index.html
            由于uri可能含有参数,在判断请求路径时不需要关注参数部分
            因此应当使用requestURI作为请求路径判定用户意图
         */
//        String path = request.getUri();
        String path = request.getRequestURI();
        System.out.println("请求路径" + path);//path:/index.html

        //是否为请求业务
        Method method = HandlerMapping.getMethod(path);
        if(method!=null){
            try {
                //通过方法对象获取其所属的类
                Class cls = method.getDeclaringClass();
                Object o = cls.newInstance();
                method.invoke(o,request,response);
            } catch (Exception e) {
                e.printStackTrace();
                //处理500
                response.setStatusCode(500);
                response.setStatusReason("Internal Server Error");
                response.setContentFile(new File(staticDir,"500.html"));
            }
        }else {
            File file = new File(staticDir, path);
            if (file.isFile()) {
                response.setStatusCode(200);
                response.setStatusReason("OK");
                response.setContentFile(file);
            } else {
                response.setStatusCode(404);
                response.setStatusReason("NotFound");
                file = new File(staticDir, "404.html");
                response.setContentFile(file);
            }
        }

    }

    public static DispatcherServlet getInstance() {
        return instance;
    }
}







